<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;

class RabbitmqReceive extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mq:receive';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $connection = new AMQPStreamConnection(env('RABBITMQ_HOST'), env('RABBITMQ_PORT'), env('RABBITMQ_LOGIN'), env('RABBITMQ_PASSWORD'));
        $channel = $connection->channel();

        $channel->queue_declare('hello1', false, false, false, false);

        echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

        $callback = function($msg) {
            echo " [x] Received ", $msg->body, "\n";
        };

        $channel->basic_consume('hello1', '', false, true, false, false, $callback);

        while(count($channel->callbacks)) {
            $channel->wait();
        }

        $channel->close();
        $connection->close();
//        /**
//         * 接收消息
//         */
//
//        $exchangeName = 'demo';
//        $queueName = 'hello';
//        $routeKey = 'hello';
//
//// 建立TCP连接
//        $connection = new \AMQPConnection([
//            'host' => env('RABBITMQ_HOST'),
//            'port' => env('RABBITMQ_PORT'),
//            'vhost' => env('RABBITMQ_VHOST'),
//            'login' => env('RABBITMQ_LOGIN'),
//            'password' => env('RABBITMQ_PASSWORD'),
//        ]);
//        $connection->connect() or die("Cannot connect to the broker!\n");
//
//        $channel = new \AMQPChannel($connection);
//
//        $exchange = new \AMQPExchange($channel);
//        $exchange->setName($exchangeName);
//        $exchange->setType(AMQP_EX_TYPE_DIRECT);
//
//        echo 'Exchange Status: ' . $exchange->declareExchange() . "\n";
//
//        $queue = new \AMQPQueue($channel);
//        $queue->setName($queueName);
//
//        echo 'Message Total: ' . $queue->declareQueue() . "\n";
//
//        echo 'Queue Bind: ' . $queue->bind($exchangeName, $routeKey) . "\n";
//
//        var_dump("Waiting for message...");
//
//        // 消费队列消息
////        while(TRUE) {
////            $queue->consume('processMessage');
////        }
//
//        // 断开连接
//        $connection->disconnect();
    }

    function processMessage($envelope, $queue) {
        $msg = $envelope->getBody();
        var_dump("Received: " . $msg);
        $queue->ack($envelope->getDeliveryTag()); // 手动发送ACK应答
    }
}
